package org.fessingapore.library.daos.impl;

import java.sql.SQLException;
import java.util.Calendar;
import java.util.List;

import org.fessingapore.library.constants.ItemType;
import org.fessingapore.library.constants.LoanStatus;
import org.fessingapore.library.daos.LoanDao;
import org.fessingapore.library.models.Loan;
import org.fessingapore.library.util.HibernateUtil;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;

public class LoanDaoImpl extends GenericDaoImpl<Loan, Integer> implements LoanDao{

	private Session session;
	
	public List<Loan> search(Loan loan) throws SQLException {
		session = HibernateUtil.getSessionFactory().openSession();
        Criteria criteria = session.createCriteria(Loan.class, "loan");
        
        if (loan.getMember() != null){
        	criteria.createAlias("loan.member", "member")
            .add(Restrictions.eq("member.id", loan.getMember().getId()));
        }
        
        if (loan.getItem() != null){
        	criteria.createAlias("loan.item", "item")
            .add(Restrictions.eq("item.id", loan.getItem().getId()));
        }
        
        if (loan.getStatus() != null) {
        	criteria.add(Restrictions.eq("item.status", loan.getStatus()));
        }
        
        List<Loan> loanList = criteria.list();
        clear();
        return loanList;
	}

	public List<Loan> findAllNewOverdue() {
		session = HibernateUtil.getSessionFactory().openSession();
        Criteria criteria = session.createCriteria(Loan.class, "loan");
        
        criteria.add(Restrictions.eq("item.status", LoanStatus.ON_LOAN))
        .add(Restrictions.lt("loan.dateToReturn", Calendar.getInstance().getTime()));
        
        List<Loan> loanList = criteria.list();
        clear();
        return loanList;
	}

}
